package com.atguigu.gmall.product.service.impl;

import com.atguigu.gmall.common.cache.GmallCache;
import com.atguigu.gmall.product.mapper.SpuSaleAttrMapper;
import com.atguigu.gmall.product.model.*;
import com.atguigu.gmall.product.service.*;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class SpuManageServiceImpl implements SpuManageService {

//    public SpuManageServiceImpl() {
//        System.err.println("----------------------------");
//    }

    @Autowired
    private SpuInfoService spuInfoService;

    @Autowired
    private SpuImageService spuImageService;

    @Autowired
    private SpuPosterService spuPosterService;

    @Autowired
    private SpuSaleAttrService spuSaleAttrService;

    @Autowired
    private SpuSaleAttrValueService spuSaleAttrValueService;

    @Autowired
    private BaseSaleAttrService baseSaleAttrService;

    @Autowired
    private SkuInfoService skuInfoService;

    @Autowired
    private SkuImageService skuImageService;

    @Autowired
    private SkuAttrValueService skuAttrValueService;

    @Autowired
    private SkuSaleAttrValueService skuSaleAttrValueService;

    /**
     * spu分页列表查询商品
     *
     * @param iPage
     * @param category3Id
     * @return
     */
    @Override
    public Page<SpuInfo> getSpuListByPage(Page<SpuInfo> iPage, Long category3Id) {
        //获取商品基本信息表spu_info
        LambdaQueryWrapper<SpuInfo> queryWrapper = new LambdaQueryWrapper<>();
        //获取category3Id
        queryWrapper.eq(SpuInfo::getCategory3Id, category3Id);
        //排序
        queryWrapper.orderByDesc(SpuInfo::getUpdateTime);

        //执行分页查询
        iPage = spuInfoService.page(iPage, queryWrapper);
        return iPage;
    }

    /**
     * 保存商品属性SPU所有信息
     * 1.将商品基本信息封装SpuInfo对象 存入spu_info表
     * 2.将提交商品图片封装到SpuImage集合中 存入spu_image表
     * 3.将提交海报图片封装到SpuPost集合中 存入spu_poster表
     * 4.将提交销售属性名称SpuSaleAttr集合 存入spu_sale_attr表
     * 5.将提交销售属性值SpuSaleAttrValue集合 存入spu_sale_attr_value表
     *
     * @param spuInfo
     * @return
     */
    @Override
    //事务注解 Exception异常
    @Transactional(rollbackFor = Exception.class)
    public void saveSpuInfo(SpuInfo spuInfo) {
        // 1.将商品基本信息封装SpuInfo对象 存入spu_info表
        spuInfoService.save(spuInfo);
        Long spuId = spuInfo.getId();
        //2.将提交商品图片封装到SpuImage集合中 存入spu_image表
        List<SpuImage> spuImageList = spuInfo.getSpuImageList();
        //获取照片集合判断是否为空
        if (!CollectionUtils.isEmpty(spuImageList)) {
            spuImageList.stream().forEach(spuImage -> {
                //为每一个商品赋值
                spuImage.setSpuId(spuId);
            });
            //保存
            spuImageService.saveBatch(spuImageList);
        }
        //3.将提交海报图片封装到SpuPost集合中 存入spu_poster表
        List<SpuPoster> spuPosterList = spuInfo.getSpuPosterList();
        //获取 商品的海报图片集合
        if (!CollectionUtils.isEmpty(spuPosterList)) {
            spuPosterList.stream().forEach(spuPoster -> {
                //为每一个海报图赋值
                spuPoster.setSpuId(spuId);
            });
            //保存
            spuPosterService.saveBatch(spuPosterList);
        }

        //4.将提交销售属性名称SpuSaleAttr集合 存入spu_sale_attr表
        List<SpuSaleAttr> spuSaleAttrList = spuInfo.getSpuSaleAttrList();
        if (!CollectionUtils.isEmpty(spuSaleAttrList)) {
            spuSaleAttrList.stream().forEach(spuSaleAttr -> {
                spuSaleAttr.setSpuId(spuId);
                //5.将提交销售属性值SpuSaleAttrValue集合 存入spu_sale_attr_value表
                List<SpuSaleAttrValue> spuSaleAttrValueList = spuSaleAttr.getSpuSaleAttrValueList();
                if (!CollectionUtils.isEmpty(spuSaleAttrValueList)) {
                    spuSaleAttrValueList.stream().forEach(spuSaleAttrValue -> {
                        //spuId
                        spuSaleAttrValue.setSpuId(spuId);
                        //赋值setSaleAttrName
                        spuSaleAttrValue.setSaleAttrName(spuSaleAttr.getSaleAttrName());
                    });
                    spuSaleAttrValueService.saveBatch(spuSaleAttrValueList);
                }
            });
            spuSaleAttrService.saveBatch(spuSaleAttrList);
        }
    }

    /**
     * 根据SPUID查询商品销售属性列表(包含属性值)
     *
     * @param spuId
     * @return
     */
    @Override
    public List<SpuSaleAttr> getSpuSaleAttrList(Long spuId) {
        //自定义sql查询
        //调用自定义SQL查询销售属性名称以及值
        SpuSaleAttrMapper spuSaleAttrMapper = (SpuSaleAttrMapper) spuSaleAttrService.getBaseMapper();
        List<SpuSaleAttr> spuSaleAttrList = spuSaleAttrMapper.getSpuSaleAttrList(spuId);
        return spuSaleAttrList;
    }


    /**
     * 根据商品SpuID查询当前商品所有图片
     *
     * @param spuId
     * @return
     */
    @Override
    public List<SpuImage> getSpuImageList(Long spuId) {
        LambdaQueryWrapper<SpuImage> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SpuImage::getSpuId, spuId);
        return spuImageService.list(queryWrapper);
    }

    /**
     * 根据id删除spu
     *
     * @param spuId
     * @return
     */

    @Override
    public void deleteSpuInfo(Long spuId) {
        //刪除spu
        spuInfoService.removeById(spuId);

        LambdaQueryWrapper<SpuImage> SpuImageQueryWrapper = new LambdaQueryWrapper<>();
        SpuImageQueryWrapper.eq(SpuImage::getSpuId, spuId);
        spuImageService.remove(SpuImageQueryWrapper);

        LambdaQueryWrapper<SpuPoster> SpuPosterQueryWrapper = new LambdaQueryWrapper<>();
        SpuPosterQueryWrapper.eq(SpuPoster::getSpuId, spuId);
        spuPosterService.remove(SpuPosterQueryWrapper);

        LambdaQueryWrapper<SpuSaleAttr> SpuSaleAttrQueryWrapper = new LambdaQueryWrapper<>();
        SpuSaleAttrQueryWrapper.eq(SpuSaleAttr::getSpuId, spuId);
        spuSaleAttrService.remove(SpuSaleAttrQueryWrapper);

        LambdaQueryWrapper<SpuSaleAttrValue> SpuSaleAttrValueQueryWrapper = new LambdaQueryWrapper<>();
        SpuSaleAttrValueQueryWrapper.eq(SpuSaleAttrValue::getSpuId, spuId);
        spuSaleAttrValueService.remove(SpuSaleAttrValueQueryWrapper);


        //删除spu下sku总和
        LambdaQueryWrapper<SkuInfo> SkuInfoQueryWrapperById = new LambdaQueryWrapper<>();
        SkuInfoQueryWrapperById.eq(SkuInfo::getSpuId, spuId);
        List<SkuInfo> list = skuInfoService.list(SkuInfoQueryWrapperById);
        List<Long> longs = new ArrayList<>();
        for (SkuInfo skuInfo : list) {
            longs.add(skuInfo.getId());
        }
        LambdaQueryWrapper<SkuImage> SkuImageQueryWrapper = new LambdaQueryWrapper<>();
        SkuImageQueryWrapper.in(SkuImage::getSkuId, longs);
        skuImageService.remove(SkuImageQueryWrapper);

        LambdaQueryWrapper<SkuAttrValue> SkuAttrValueQueryWrapper = new LambdaQueryWrapper<>();
        SkuAttrValueQueryWrapper.in(SkuAttrValue::getSkuId, longs);
        skuAttrValueService.remove(SkuAttrValueQueryWrapper);

        LambdaQueryWrapper<SkuSaleAttrValue> SkuSaleAttrValueQueryWrapper = new LambdaQueryWrapper<>();
        SkuSaleAttrValueQueryWrapper.in(SkuSaleAttrValue::getSkuId, longs);
        skuSaleAttrValueService.remove(SkuSaleAttrValueQueryWrapper);

        LambdaQueryWrapper<SkuInfo> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SkuInfo::getSpuId, spuId);
        skuInfoService.remove(queryWrapper);
    }

//    @Test
//    public List<Long> aa(Long spuId) {
//
//
//        LambdaQueryWrapper<SkuInfo> SkuInfoQueryWrapperById = new LambdaQueryWrapper<>();
//        SkuInfoQueryWrapperById.eq(SkuInfo::getSpuId, spuId);
//        List<SkuInfo> list = skuInfoService.list(SkuInfoQueryWrapperById);
////        HashMap<String, Object> stringLongHashMap = new HashMap<>();
//        List<Long> longs = new ArrayList<>();
//        for (SkuInfo skuInfo : list) {
////            stringLongHashMap.put("sku_id", skuInfo.getId());
//            longs.add(skuInfo.getId());
//        }
//
//
//        LambdaQueryWrapper<SkuImage> SkuImageQueryWrapper = new LambdaQueryWrapper<>();
//        SkuImageQueryWrapper.in(SkuImage::getSkuId, longs);
//        // List<SkuImage> list1 = skuImageService.list(SkuImageQueryWrapper);
//        // List<Long> skuImageIds = new ArrayList<>();
//        // for (SkuImage skuImage : list1) {
//        //     skuImageIds.add(skuImage.getId());
//        // }
////
////        skuImageService.removeByIds(skuImageIds);
//        skuImageService.remove(SkuImageQueryWrapper);
//
////        skuImageService.removeByMap(stringLongHashMap);
//        return null;
//
//    }

    /**
     * 根据spuId获取海报数据
     *
     * @param spuId
     * @return
     */
    @Override
    @GmallCache(prefix = "spuPoster:")
    public List<SpuPoster> getSpuPosterBySpuId(Long spuId) {
        LambdaQueryWrapper<SpuPoster> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SpuPoster::getSpuId, spuId);
        List<SpuPoster> list = spuPosterService.list(queryWrapper);
        return list;
    }

    /**
     * 查询SPU所有销售属性,将指定传入SKU商品销售属性区分是否选中/排序
     *
     * @param skuId
     * @param spuId
     * @return
     */
    @Override
    @GmallCache(prefix = "spuSaleAttrList:")
    public List<SpuSaleAttr> getSpuSaleAttrListCheckBySku(Long skuId, Long spuId) {
        //获取spuSaleAttrService.Mapper对象
        SpuSaleAttrMapper spuSaleAttrBaseMapper = (SpuSaleAttrMapper) spuSaleAttrService.getBaseMapper();
        //自定义SQL查询 返回list
        List<SpuSaleAttr> list = spuSaleAttrBaseMapper.getSpuSaleAttrListCheckBySku(skuId, spuId);
        return list;
    }


    /**
     * 查询每个商品SKU 销售属性 跟 SKUID 对照关系
     *
     * @param spuId
     * @return
     */
    @Override
    @GmallCache(prefix = "skuValueIdsMap:")
    public Map<String, String> getSkuValueIdsMap(Long spuId) {
        HashMap<String, String> mapResult = new HashMap<>();
        //获取spuSaleAttrService.Mapper对象
        SpuSaleAttrMapper spuSaleAttrBaseMapper = (SpuSaleAttrMapper) spuSaleAttrService.getBaseMapper();
        //自定义SQL查询  返回mapList  sku_id  value_ids
        List<Map<String, Object>> mapList = spuSaleAttrBaseMapper.getSkuValueIdsMap(spuId);
        if (!CollectionUtils.isEmpty(mapList)) {
            mapList.stream().forEach(skuAttrValueMap -> {
                //mapList取 sku_id  value_ids赋值给 mapResult
                String skuId = skuAttrValueMap.get("sku_id").toString();
                String valueIds = skuAttrValueMap.get("value_ids").toString();
                mapResult.put(valueIds, skuId);
            });
        }
        return mapResult;
    }

}
